/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import javax.swing.JOptionPane;
import dao.CidadeDAO;
import bean.Cidade;
import static java.lang.Character.toUpperCase;
import java.util.List;
import java.util.regex.Pattern;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import org.hibernate.Session;
import util.HibernateUtil;

/**
 *
 * @author Charles Gesser
 */
public class CadastroCidade extends javax.swing.JFrame {

    private Cidade maipular;

    /**
     * Creates new form CadastroCidade
     */
    public CadastroCidade() {

        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
        initComponents();
        this.setLocationRelativeTo(this);
        jTcodigo.setText("");
        jTnomecidade.requestFocus();
        jtbExcluir.setVisible(false);
        buscarid();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTnomecidade = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jTibge = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTcodigo = new javax.swing.JTextField();
        jbCadastrar = new javax.swing.JToggleButton();
        jToggleButton4 = new javax.swing.JToggleButton();
        jToggleButton5 = new javax.swing.JToggleButton();
        jtbExcluir = new javax.swing.JToggleButton();
        jTestado = new javax.swing.JTextField();
        jtBbuscarCidade = new javax.swing.JToggleButton();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setResizable(false);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cadastro De Cidade"));

        jTnomecidade.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTnomecidadeMouseClicked(evt);
            }
        });
        jTnomecidade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTnomecidadeActionPerformed(evt);
            }
        });
        jTnomecidade.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jTnomecidadeFocusGained(evt);
            }
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTnomecidadeFocusLost(evt);
            }
        });

        jLabel1.setText("Cidade:");

        jLabel2.setText("Estado:");

        jLabel3.setText("IBGE:");

        jLabel5.setText("Código:");

        jTcodigo.setEnabled(false);

        jbCadastrar.setText("Cadastrar");
        jbCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCadastrarActionPerformed(evt);
            }
        });

        jToggleButton4.setText("Limpar Campos");
        jToggleButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton4ActionPerformed(evt);
            }
        });

        jToggleButton5.setText("Sair");
        jToggleButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jToggleButton5ActionPerformed(evt);
            }
        });

        jtbExcluir.setText("excluir");
        jtbExcluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtbExcluirActionPerformed(evt);
            }
        });
        jtbExcluir.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jtbExcluirKeyReleased(evt);
            }
        });

        jTestado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTestadoActionPerformed(evt);
            }
        });
        jTestado.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTestadoFocusLost(evt);
            }
        });
        jTestado.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTestadoKeyPressed(evt);
            }
        });

        jtBbuscarCidade.setText("Buscar Cidade");
        jtBbuscarCidade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtBbuscarCidadeActionPerformed(evt);
            }
        });

        jButton1.setText("jButton1");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addGap(18, 18, 18)
                        .addComponent(jTcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jtBbuscarCidade)
                        .addGap(68, 68, 68))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(86, 86, 86)
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jToggleButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jTnomecidade)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jTestado, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE)
                                .addComponent(jTibge, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                                .addComponent(jbCadastrar)
                                .addGap(52, 52, 52)
                                .addComponent(jtbExcluir)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jToggleButton4)))))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTcodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jtBbuscarCidade)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTnomecidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jTibge, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTestado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(27, 27, 27)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbCadastrar)
                    .addComponent(jtbExcluir)
                    .addComponent(jToggleButton4))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jToggleButton5)
                    .addComponent(jButton1))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 14, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jToggleButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton5ActionPerformed
        dispose();
    }//GEN-LAST:event_jToggleButton5ActionPerformed

    private void jbCadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCadastrarActionPerformed

        Cidade cadastrocidade = new Cidade();
        CidadeDAO obj_cidade = new CidadeDAO();

        cadastrocidade.setCidCod(Integer.parseInt(jTcodigo.getText()));
        cadastrocidade.setCidNom(jTnomecidade.getText());
        cadastrocidade.setCidEst(jTestado.getText());
        cadastrocidade.setCidIbge(jTibge.getText());

        obj_cidade.inserCidade(cadastrocidade);

        jToggleButton4ActionPerformed(evt);

        JOptionPane.showMessageDialog(rootPane, "Cadastrado");
    }//GEN-LAST:event_jbCadastrarActionPerformed

    private void jToggleButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton4ActionPerformed

        jTcodigo.setText("");
        jTnomecidade.setText("");
        jTestado.setText("");
        jTibge.setText("");
        jtbExcluir.setVisible(false);
        jTnomecidade.requestFocus();

    }//GEN-LAST:event_jToggleButton4ActionPerformed

    private void jTnomecidadeFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTnomecidadeFocusGained
    }//GEN-LAST:event_jTnomecidadeFocusGained

    private void jtbExcluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtbExcluirActionPerformed

        CidadeDAO obj_cidade = new CidadeDAO();
        //JOptionPane.showMessageDialog(null, "Chegou no metodo exclui");
        //obj_cidade.fecharSessao();
        obj_cidade.excluiCidade(maipular);

        jToggleButton4ActionPerformed(evt);
        JOptionPane.showMessageDialog(rootPane, "Excluido");
        jTnomecidade.requestFocus();
        jtbExcluir.setVisible(false);

    }//GEN-LAST:event_jtbExcluirActionPerformed

    private void jTestadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTestadoActionPerformed
    }//GEN-LAST:event_jTestadoActionPerformed

    private void jTestadoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTestadoFocusLost

        String valida = Pattern.compile("[^a-z , ^A-Z]").matcher(jTestado.getText()).replaceAll("");
        if (valida.equals("") || valida == null || jTestado.getText().length() == 1) {
            jTestado.setText("");
            JOptionPane.showMessageDialog(null, "Digite a sigla do estado");
            jTestado.requestFocus();
        } else {
            jTestado.setText(valida);
            jTestado.setText(jTestado.getText().toUpperCase());
        }
    }//GEN-LAST:event_jTestadoFocusLost

    private void jTestadoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTestadoKeyPressed
        if (jTestado.getText().length() == 2) {
            jTestado.setText(jTestado.getText().substring(0, 1));
        }
    }//GEN-LAST:event_jTestadoKeyPressed

    private void jTnomecidadeFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTnomecidadeFocusLost
        jTnomecidade.setText(jTnomecidade.getText().toUpperCase());
    }//GEN-LAST:event_jTnomecidadeFocusLost

    private void jtBbuscarCidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtBbuscarCidadeActionPerformed
        BuscaCidade busc = new BuscaCidade();
        busc.setVisible(true);
        this.dispose();
    }//GEN-LAST:event_jtBbuscarCidadeActionPerformed

    private void jTnomecidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTnomecidadeActionPerformed
        if (jTnomecidade.getText() == "") {
            buscarid();
        }
    }//GEN-LAST:event_jTnomecidadeActionPerformed

    private void jTnomecidadeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTnomecidadeMouseClicked
    }//GEN-LAST:event_jTnomecidadeMouseClicked

    private void jtbExcluirKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jtbExcluirKeyReleased
    }//GEN-LAST:event_jtbExcluirKeyReleased

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        Session session = HibernateUtil.getSession();
        List<Cidade> lista = session.createCriteria(Cidade.class).list();
        for (Cidade c : lista) {
            if (c.getCidCod() == Integer.parseInt(jTcodigo.getText()) ) {
                session.beginTransaction();
                session.delete(c);
                session.getTransaction().commit();

            }
        }
        session.flush();
        session.close();
// TODO add your handling code here:
    }//GEN-LAST:event_jButton1ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastroCidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastroCidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastroCidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastroCidade.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CadastroCidade().setVisible(true);
            }
        });

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTcodigo;
    private javax.swing.JTextField jTestado;
    private javax.swing.JTextField jTibge;
    private javax.swing.JTextField jTnomecidade;
    private javax.swing.JToggleButton jToggleButton4;
    private javax.swing.JToggleButton jToggleButton5;
    private javax.swing.JToggleButton jbCadastrar;
    private javax.swing.JToggleButton jtBbuscarCidade;
    private javax.swing.JToggleButton jtbExcluir;
    // End of variables declaration//GEN-END:variables

    public void recebe(int i) {
        CidadeDAO cid = new CidadeDAO();

        List<Cidade> listaCidade = cid.todas_cidade();
        for (Cidade c : listaCidade) {
            if (c.getCidCod() == i) {
                jTcodigo.setText(String.valueOf(c.getCidCod()));
                jTnomecidade.setText(c.getCidNom());
                jTibge.setText(c.getCidIbge());
                jTestado.setText(c.getCidEst());
                jtbExcluir.setVisible(true);

                maipular = c;
            }
        }
    }

    private void buscarid() {
        CidadeDAO cidademaoircodigo = new CidadeDAO();
        int codigoId = cidademaoircodigo.maiorID();
        jTcodigo.setText(String.valueOf(codigoId));
        cidademaoircodigo.fecharSessao();

    }

}
